package com.yuke.cloud.service.uac.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.dto.LoginAuthDto;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.uac.dao.AccRoleMapper;
import com.yuke.cloud.service.uac.dto.RoleMainQueryDto;
import com.yuke.cloud.service.uac.entity.AccRole;
import com.yuke.cloud.service.uac.entity.AccUserRole;
import com.yuke.cloud.service.uac.service.AccRoleMenuService;
import com.yuke.cloud.service.uac.service.AccRolePermissionService;
import com.yuke.cloud.service.uac.service.AccRoleService;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.service.uac.service.AccUserRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * Created by wg on 2018/11/05.
 */
@Service
@Transactional
public class AccRoleServiceImpl extends BaseService<AccRole> implements AccRoleService {
    @Resource
    private AccRoleMapper accRoleMapper;

    @Resource
    private AccUserRoleService accUserRoleService;
    @Resource
    private AccRoleMenuService accRoleMenuService;
    @Resource
    private AccRolePermissionService accRolePermissionService;

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public PageInfo queryRoleListWithPage(RoleMainQueryDto role) {

        AccRole accRole = new AccRole();
        BeanUtils.copyProperties(role, accRole);
        accRole.setOrderBy("update_time desc");
        PageHelper.startPage(role.getPageNum(), role.getPageSize());
        List<AccRole> roleList = accRoleMapper.queryRoleListWithPage(accRole);
        return new PageInfo<>(roleList);
    }

    @Override
    public int deleteRoleById(Long roleId) {
        //查询该角色下是否有用户绑定, 有的话提醒不能删除
        if (null == roleId) {
            throw new IllegalArgumentException(ErrorCodeEnum.UAC10012001.msg());
        }

        // 超级管理员不能删除
        if (Objects.equals(roleId, GlobalConstant.Sys.SUPER_MANAGER_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        // add by wg 20181124
        // 系统角色不能删除
        if (Objects.equals(roleId, GlobalConstant.Sys.ADMIN_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.WAREHOUSE_ADMIN_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.PRODUCT_ADMIN_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.SHOP_ADMIN_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.WAREHOUSE_OPERATOR_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.CONSUMER_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.SELLER_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.SUPPLIER_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        if (Objects.equals(roleId, GlobalConstant.Sys.CONTENT_ADMIN_ROLE_ID)) {
            throw new UacBizException(ErrorCodeEnum.UAC10012003);
        }

        List<AccUserRole> urList = accUserRoleService.listByRoleId(roleId);

        if (!urList.isEmpty()) {
            accUserRoleService.deleteByRoleId(roleId);
        }

        accRolePermissionService.deleteByRoleId(roleId);
        accRoleMenuService.deleteByRoleId(roleId);
        return accRoleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void batchDeleteByIdList(List<Long> roleIdList) {
        logger.info("批量删除角色. idList={}", roleIdList);
        Preconditions.checkArgument(PublicUtil.isNotEmpty(roleIdList), "删除角色ID不存在");

        List<AccUserRole> uruList = accUserRoleService.listByRoleIdList(roleIdList);
        if (!uruList.isEmpty()) {
            accUserRoleService.deleteByRoleIdList(roleIdList);
        }

        accRoleMenuService.deleteByRoleIdList(roleIdList);
        accRolePermissionService.deleteByRoleIdList(roleIdList);

        Example example = new Example(AccRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("roleId", roleIdList);
        int result = accRoleMapper.deleteByExample(example);
        if (result < roleIdList.size()) {
            throw new UacBizException(ErrorCodeEnum.UAC10012007, Joiner.on(GlobalConstant.Symbol.COMMA).join(roleIdList));
        }
    }

    @Override
    public int saveRole(AccRole role, LoginAuthDto loginAuthDto) {
        int result = 0;
        if (null == role.getRoleId()) {
            Long roleId = super.generateId();
            role.setRoleId(roleId);
            role.setCreateId(loginAuthDto.getUserId());
            role.setCreateTime(new Date());
            result = accRoleMapper.insertSelective(role);
        } else {
            role.setUpdateId(loginAuthDto.getUserId());
            role.setUpdateTime(new Date());
            result = accRoleMapper.updateByPrimaryKeySelective(role);
            if (result < 1) {
                throw new UacBizException(ErrorCodeEnum.UAC10014003);
            }
        }

        return result;
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public AccRole getRoleById(Long roleId) {
        return accRoleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    @Transactional(readOnly = true, rollbackFor = Exception.class)
    public List<AccRole> findAllRoleInfoByUserId(Long userId) {
        return accRoleMapper.selectAllRoleInfoByUserId(userId);
    }

}
